package com.seuic.hnjiningposapp.hnapps.ui.activity;


import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.Utils;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.seuic.hnjiningposapp.R;
import com.seuic.hnjiningposapp.hnapps.base.BaseActivity;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.ActivationInputPopup;
import com.seuic.hnjiningposapp.hnapps.ui.view.dialog.SingInPopup;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtils;
import com.seuic.hnjiningposapp.hnapps.util.HttpUtilsV2;
import com.socks.library.KLog;


import static com.seuic.hnjiningposapp.hnapps.util.Api.RETURN_CODE_SUCCEED;


/**
 * 激活页面
 *
 * @author rainking
 */
public class ActivateActivity extends BaseActivity {

    private ActivationInputPopup activationInputPopup;
    private BasePopupView activationInputPopupView;
    private SingInPopup singinPopup;
    private BasePopupView singInPopupView;

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_activate;
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        findViewById(R.id.base_back_btn).setVisibility(View.INVISIBLE);
        this.setTitleText("设备激活");
        activationInputPopup = new ActivationInputPopup(ActivateActivity.this, ActivateActivity.this, (TdgBrah, OperTellerNo, TellerPwd, DvcNum, key1, key2) -> {
            String primarySecretKey = HttpUtils.getPrimarySecretKey(key1, key2);
            KLog.e(primarySecretKey + "primarySecretKey");
            if (!TextUtils.isEmpty(primarySecretKey)) {
                SPStaticUtils.put("primarySecretKey", primarySecretKey);
                HttpUtilsV2.getDeviceActivation(TdgBrah, OperTellerNo, TellerPwd, DvcNum, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                        equipmentInquiry();
                    }

                    @Override
                    public void onError(String code, String msg) {
                        activationInputPopup.recover();
                        showErrorPopup(msg);
                    }
                });
            } else {
                showErrorPopup("主秘钥生成失败请重新尝试激活", () -> activationInputPopup.recoverActivate());
            }
        });
        activationInputPopupView = new XPopup.Builder(ActivateActivity.this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isRequestFocus(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                //信息输入界面
                .asCustom(activationInputPopup);
        singinPopup = new SingInPopup(ActivateActivity.this, ActivateActivity.this);
        singinPopup.setOnSingInListener(this::getSingIn);
        singInPopupView = new XPopup.Builder(ActivateActivity.this)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .isRequestFocus(false)
                .moveUpToKeyboard(false)
                .hasShadowBg(false)
                .hasStatusBarShadow(false)
                //激活界面
                .asCustom(singinPopup);

    }

    @Override
    protected void onResume() {
        super.onResume();
        //联网检查设备是否激活
        showLoadingPopup("自动检测中...", this::equipmentInquiry);
    }

    /**
     * 设备查询
     */
    private void equipmentInquiry() {
        HttpUtilsV2.getEquipmentInquiry(new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                setTitleText("签到");
                //机构号、网点号
                KLog.json(JSON.toJSONString(rspBody));
                SPStaticUtils.put("TdgBrah", rspBody.getString("TdgBrah"));
                //机构名称、网点名称
                SPStaticUtils.put("TdgBrahName", rspBody.getString("TdgBrahName"));
                //设备编码
                SPStaticUtils.put("DeviceNum", rspBody.getString("DeviceNum"));
                //设备代码
                SPStaticUtils.put("DvcNum", rspBody.getString("DvcNum"));
                getWorkKey();


            }

            @Override
            public void onError(String code, String msg) {
                if (code.equals("FSS006")) {
                    setTitleText("设备激活");
                    SPStaticUtils.clear();
                    if (singInPopupView != null && singInPopupView.isShow()) {
                        singInPopupView.dismiss();
                    }
                    if (!activationInputPopupView.isShow()) {
                        activationInputPopupView.show();//输入上诉要素界面
                    }
                } else {
                    showErrorPopup(msg);
                }
            }
        });
    }

    /**
     * 获取工作工作秘钥
     */
    private void getWorkKey() {
        HttpUtilsV2.getWorkKey(new HttpUtilsV2.NetCallBack() {
            @Override
            public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {
                //PIN密钥密文
                SPStaticUtils.put("TPK", rspBody.getString("TPK"));
                KLog.e("获取工作秘钥：" + SPStaticUtils.getString("TPK"));
                //PIN密钥校验值
                SPStaticUtils.put("TPKCheckValue", rspBody.getString("TPKCheckValue"));
                //MAC密钥密文
                SPStaticUtils.put("TAK", rspBody.getString("TAK"));
                //MAC密钥校验值
                SPStaticUtils.put("TAKCheckValue", rspBody.getString("TAKCheckValue"));


                if (singInPopupView != null && !singInPopupView.isShow()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            activationInputPopupView.dismiss();
                            singInPopupView.show();//展示签到
                        }
                    });
                }
            }

            @Override
            public void onError(String code, String msg) {
                showErrorPopup(msg);
            }
        });
    }


    private void getSingIn(String account, String pwd) {
        HttpUtilsV2.getSignIn(account,
                pwd, new HttpUtilsV2.NetCallBack() {
                    @Override
                    public void onSuccess(String ServerSeqNo, String ConsumerSeqNo, JSONObject rspBody) {

                        SPStaticUtils.put("ManagerNum", account);

                        KLog.e("存款次数限制" + rspBody.getString("DEPOSIT_COUNT_LIMIT"));
                        KLog.e("存款金额限制" + rspBody.getString("DEPOSIT_AMOUNT_LIMIT"));

                        KLog.e("取款次数限制" + rspBody.getString("TRADE_DRAWALCOUNT_LIMIT"));
                        KLog.e("取款金额限制" + rspBody.getString("TRADE_AMOUNT_LIMIT"));

                        KLog.e("转账次数限制" + rspBody.getString("TRADE_COUNT_LIMIT"));
                        KLog.e("转账金额限制" + rspBody.getString("TRADE_TRANSFER_LIMIT"));


                        //交易柜员号，在机具上特指虚拟柜员号
                        SPStaticUtils.put("TranTellerNo", rspBody.getString("tellerNo"));
                        SPStaticUtils.put("CardNum", rspBody.getString("CardNum"));
                        SPStaticUtils.put("CardNumUserName", rspBody.getString("userName"));
                        SPStaticUtils.put("CardNumUserNo", rspBody.getString("userNo"));
                        //转账次数限制
                        SPStaticUtils.put("TRADE_COUNT_LIMIT", rspBody.getString("TRADE_COUNT_LIMIT"));
                        //取款金额限制
                        SPStaticUtils.put("TRADE_AMOUNT_LIMIT", rspBody.getString("TRADE_AMOUNT_LIMIT"));
                        //转账金额限制
                        SPStaticUtils.put("TRADE_TRANSFER_LIMIT", rspBody.getString("TRADE_TRANSFER_LIMIT"));
                        //取款次数限制
                        SPStaticUtils.put("TRADE_DRAWALCOUNT_LIMIT", rspBody.getString("TRADE_DRAWALCOUNT_LIMIT"));
                        //存款次数限制
                        SPStaticUtils.put("DEPOSIT_COUNT_LIMIT", rspBody.getString("DEPOSIT_COUNT_LIMIT"));
                        //存款金额限制
                        SPStaticUtils.put("DEPOSIT_AMOUNT_LIMIT", rspBody.getString("DEPOSIT_AMOUNT_LIMIT"));
                        //进入主页
                        finish();
                        ActivityUtils.startActivity(HomeActivity.class);
                    }

                    @Override
                    public void onError(String code, String msg) {
                        singinPopup.recover();
                        showErrorPopup(msg);
                    }
                });
    }

    @Override
    public void initEvent(Bundle savedInstanceState) {

    }


}
